package com.gitee.wsl.android.ext.okhttp.response

import android.net.Uri
import com.gitee.wsl.android.file.FileManager
import com.gitee.wsl.jvm.okhttp.response.ResponseMapper
import com.gitee.wsl.jvm.okhttp.response.hasBody
import okhttp3.Response
import okio.sink


/**
 *
 */
class FileResponseMapper(val fileName:String?=null) : ResponseMapper<Uri?> {
    override fun map(response: Response): Uri? {
        val realFileName = fileName?:response.request.url.pathSegments.lastOrNull()
        if(response.hasBody())
            return response.body?.let { responseBody ->
                try {
                    FileManager.createCacheFile(realFileName) {
                        val bufferedSource = responseBody.source()
                        it.sink().write(bufferedSource.buffer, responseBody.contentLength())
                    }
                }catch (e:Exception){
                    null
                }
            }
        return null
    }
}